from ..myModels.preOrderModel import *
from ..myModels.cartModel import *
from ..utils.utils import *

from drf_yasg.utils import swagger_auto_schema
from drf_yasg import openapi
from rest_framework.decorators import api_view
from rest_framework.response import Response

@api_view(['get'])
def pre_order_all(request):
    return success('all')

@api_view(['get'])
def pre_order_detail(request):
    try:
        pre_order_id = get_param(request, 'id')
        if not pre_order_id:
            return fail('缺少id')
        pre_order = PreOrder.objects.filter(id=pre_order_id).first()
        if not pre_order:
            return fail('预订单不存在')

        # 查询购物车信息
        cart_id = pre_order.cart_id.split(',')
        carts = Cart.objects.filter(id__in=cart_id).values()
        res_data = m_to_d(pre_order)
        res_data['carts'] = change_key_for_list(list(carts))
        res_data['cartId'] = res_data['cart_id'].split(',')
        return success(res_data)
    except Exception as e:
        return fail(str(e))

@api_view(['post'])
def pre_order_add(request):
    user_id = request.session.get('session')
    cart_id = get_param(request, 'cartId')
    total_money = get_param(request, 'totalMoney')
    data = {
        "cart_id": cart_id,
        "discount": 0.8,
        "expressFee": 1000,
        "full_reduce_money": 10000,
        "total_money": total_money,
        "user_id": user_id,
        "cart_id": cart_id,
        "total_money": total_money
    }
    pre_order = PreOrder.objects.create(**data)
    print(pre_order.id)
    # for i in pre_order:
    #     print(i)
    data["id"] = pre_order.id
    return success(data)

@api_view(['post'])
def pre_order_del(request):
    return success('del')

@api_view(['post'])
def pre_order_update(request):
    return success('update')
